/*
 * DocsEditor.java
 * 
 * Copyright (c) 2007
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.dcarew.googledocs.editor;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.OpenWindowListener;
import org.eclipse.swt.browser.TitleEvent;
import org.eclipse.swt.browser.TitleListener;
import org.eclipse.swt.browser.WindowEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.internal.browser.BrowserViewer;
import org.eclipse.ui.internal.browser.IBrowserViewerContainer;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.PropertySheetPage;

import com.google.gdata.data.spreadsheet.SpreadsheetEntry;

/**
 * 
 * 
 * @author Devon Carew
 */
public class SpreadsheetEditor
	extends EditorPart
	implements ISelectionProvider
{
	public static final String EDITOR_ID = "org.dcarew.googledocs.editor.SpreadsheetEditor";
	
	private BrowserViewer webBrowser;
	
	private boolean disposed;
	
	
	public SpreadsheetEditor()
	{
		
	}
	
	public Object getAdapter(final Class adapter)
	{
		if (adapter == SpreadsheetEntry.class)
			return ((DocsEditorInput)getEditorInput()).getSpreadsheet();
		
		if (adapter == IPropertySheetPage.class)
			return new PropertySheetPage();
		
		// TODO: support the Outline view
		if (adapter == IContentOutlinePage.class)
			return null;
		
		return super.getAdapter(adapter);
	}
	
	public void doSave(IProgressMonitor monitor)
	{
		// We never become dirty -
		
	}

	public void doSaveAs()
	{
		throw new UnsupportedOperationException("save as not supported");
	}
	
	public void init(IEditorSite site, IEditorInput input)
		throws PartInitException
	{
		setSite(site);
		setInput(input);
		
		setPartName(input.getName());
		
		getSite().setSelectionProvider(this);
	}

	public boolean isDirty()
	{
		return false;
	}

	public boolean isSaveAsAllowed()
	{
		return false;
	}

	public void createPartControl(Composite parent)
	{
		webBrowser = new BrowserViewer(parent, SWT.BORDER);
		
		// Listen for open browser requests and cancel them.
		webBrowser.getBrowser().addOpenWindowListener(new OpenWindowListener() {
			public void open(WindowEvent event) {
				event.required = true;
				event.browser = null;
			}
		});
		
		webBrowser.getBrowser().addTitleListener(new TitleListener() {
            public void changed(TitleEvent event) {
                setPartName(normalizeTitle(event.title));
            }
        });
		
		webBrowser.setContainer(new IBrowserViewerContainer() {
			public boolean close() {
				asyncClose();
				
				return true;
			}
			public IActionBars getActionBars() {
		        return getEditorSite().getActionBars();
			}
			public void openInExternalBrowser(String url) {
			}
		});
		
		initBrowserLocation();
	}
	
	public void setFocus()
	{
		webBrowser.setFocus();
	}
	
	public void dispose()
	{
		// TODO: somehow give the page time to save?
		
		
		disposed = true;
		
		super.dispose();
	}

	// ISelectionProvider
	public void addSelectionChangedListener(ISelectionChangedListener listener)
	{
		
	}
	
	public void removeSelectionChangedListener(ISelectionChangedListener listener)
	{
		
	}
	
	public ISelection getSelection()
	{
		DocsEditorInput editorInput = (DocsEditorInput)getEditorInput();
		
		return new StructuredSelection(editorInput.getSpreadsheet());
	}
	
	public void setSelection(ISelection selection)
	{
		
	}
	
	private void asyncClose()
	{
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				if (!disposed) {
					getSite().getPage().closeEditor(SpreadsheetEditor.this, false);
				}
			}
		});
	}
	
	private String normalizeTitle(String newTitle)
	{
		DocsEditorInput editorInput = (DocsEditorInput)getEditorInput();
		final String 	matchText 	= "- Google Docs";
		
		if (newTitle == null || newTitle.startsWith("http:"))
			return editorInput.getName();
		
		if (newTitle.indexOf(matchText) != -1)
			return newTitle.substring(0, newTitle.indexOf(matchText)).trim();
		
		return newTitle;
	}
	
	private void initBrowserLocation()
	{
		DocsEditorInput editorInput = (DocsEditorInput)getEditorInput();
		
		if (editorInput.getSpreadsheet() != null)
		{
			SpreadsheetEntry spreadsheet = editorInput.getSpreadsheet();
			
			String href = spreadsheet.getSpreadsheetLink().getHref();
			
			if (!webBrowser.isDisposed())
				webBrowser.setURL(href);
		}
		else
		{
			if (!webBrowser.isDisposed())
				webBrowser.setURL("http://docs.google.com/");
		}
	}
	
}
